package com.yystudy.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yystudy.model.system.SysRole;
import com.yystudy.model.system.SysUserRole;
import com.yystudy.model.vo.AssginRoleVo;
import com.yystudy.model.vo.SysRoleQueryVo;
import com.yystudy.system.mapper.SysRoleMapper;
import com.yystudy.system.service.SysRoleService;
import com.yystudy.system.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysUserRoleService sysUserRoleService;


    @Override
    public IPage<SysRole> selectPage(Page<SysRole> sysRolePage, SysRoleQueryVo sysRoleQueryVo) {
        return baseMapper.selectPage(sysRolePage,sysRoleQueryVo);
    }


    /**
     * 根据用户id获取角色
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> getRoleByUserId(Long userId) {
        //获取所有角色数据
        List<SysRole> sysRoles = baseMapper.selectList(null);

        LambdaQueryWrapper<SysUserRole> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysUserRole::getUserId,userId);

        //查询该用户对应的所有记录
        List<SysUserRole> list = sysUserRoleService.list(lqw);

        List<String> roleIds = new ArrayList<>();
        for (SysUserRole sysUserRole : list) {
            roleIds.add(sysUserRole.getRoleId().toString());
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("allRoles",sysRoles);
        map.put("userRoleIds",roleIds);
        return map;

    }

    /**
     * 给用户分配角色
     * @param assginRoleVo
     */
    @Override
    public void doAssign(AssginRoleVo assginRoleVo) {
        //分两步

        //第一步：先删除原本用户对应的角色记录
        LambdaQueryWrapper<SysUserRole> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysUserRole::getUserId,assginRoleVo.getUserId());
        sysUserRoleService.remove(lqw);

        //第二步：再插入新数据
        List<SysUserRole> list = new ArrayList<>();
        for (Long roleId : assginRoleVo.getRoleIdList()) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(assginRoleVo.getUserId());
            sysUserRole.setRoleId(roleId);
            list.add(sysUserRole);
        }
        sysUserRoleService.saveBatch(list);
    }


}
